<template>
  <el-dialog
    title="教师排序管理"
    v-model="dialogVisible"
    width="60%"
    :before-close="handleClose"
    class="teacher-sorting-dialog"
  >
    <div class="sorting-container" v-loading="loading">
      <el-alert
        title="操作说明"
        type="info"
        :closable="false"
        show-icon
        class="mb-4"
      >
        <template #default>
          <p>• 拖拽教师卡片调整排序</p>
          <p>• 勾选"主要教师"标记主讲教师</p>
          <p>• 至少需要设置一位主要教师</p>
        </template>
      </el-alert>

      <div class="mission-info mb-4">
        <el-card>
          <template #header>
            <span>教学任务信息</span>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="课程名称">{{ missionData.courseName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="学期">{{ missionData.termName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="专业">{{ missionData.majorName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="培养层次">{{ missionData.cengCiName || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-card>
      </div>

      <div class="teachers-section">
        <h3 class="section-title">
          <el-icon><User /></el-icon>
          授课教师排序 ({{ teacherList.length }}人)
        </h3>
        
        <div v-if="teacherList.length === 0" class="empty-teachers">
          <el-empty description="暂无分配教师"></el-empty>
        </div>

        <div v-else class="teacher-list">
          <div 
            v-for="(teacher, index) in teacherList" 
            :key="teacher.id"
            class="teacher-item"
            :class="{ 'dragging': dragIndex === index }"
            draggable="true"
            @dragstart="handleDragStart(index, $event)"
            @dragend="handleDragEnd"
            @dragover="handleDragOver"
            @drop="handleDrop(index, $event)"
          >
            <div class="drag-handle">
              <el-icon><DCaret /></el-icon>
            </div>
            
            <div class="teacher-info">
              <div class="teacher-basic">
                <div class="teacher-name">
                  <span class="name">{{ teacher.name }}</span>
                  <el-tag v-if="teacher.isPrimary" type="primary" size="small" effect="dark">
                    主要教师
                  </el-tag>
                </div>
                <div class="teacher-details">
                  <span class="detail-item">工号: {{ teacher.workNumber || '-' }}</span>
                  <span class="detail-item">职称: {{ teacher.title || '-' }}</span>
                  <span class="detail-item">部门: {{ teacher.departmentName || '-' }}</span>
                </div>
              </div>
              
              <div class="teacher-actions">
                <div class="sort-info">
                  <span class="sort-label">排序: </span>
                  <el-tag type="info" size="small">{{ index + 1 }}</el-tag>
                </div>
                
                <el-checkbox
                  v-model="teacher.isPrimary"
                  @change="handlePrimaryChange(teacher, $event)"
                  class="primary-checkbox"
                >
                  主要教师
                </el-checkbox>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSave"
          :loading="saving"
          :disabled="!hasValidPrimary"
        >
          保存排序
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { User, DCaret } from '@element-plus/icons-vue'
import { teachingMissionApi } from '@/api/teaching-mission'

export default {
  name: 'TeacherSortingDialog',
  components: {
    User,
    DCaret
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    missionId: {
      type: [String, Number],
      default: null
    },
    missionData: {
      type: Object,
      default: () => ({})
    },
    teachers: {
      type: Array,
      default: () => []
    }
  },
  emits: ['update:visible', 'close', 'success'],
  setup(props, { emit }) {
    const dialogVisible = ref(props.visible)
    const loading = ref(false)
    const saving = ref(false)
    const teacherList = ref([])
    const dragIndex = ref(-1)

    // 检查是否有有效的主要教师
    const hasValidPrimary = computed(() => {
      return teacherList.value.some(teacher => teacher.isPrimary)
    })

    // 监听对话框显示状态
    watch(() => props.visible, (newVal) => {
      dialogVisible.value = newVal
      if (newVal) {
        initTeacherList()
      }
    })

    // 监听本地对话框状态变化
    watch(dialogVisible, (newVal) => {
      emit('update:visible', newVal)
      if (!newVal) {
        emit('close')
      }
    })

    // 初始化教师列表
    const initTeacherList = () => {
      teacherList.value = props.teachers.map((teacher, index) => ({
        ...teacher,
        sortOrder: teacher.sortOrder || index + 1,
        isPrimary: teacher.isPrimary || false
      })).sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0))
    }

    // 拖拽开始
    const handleDragStart = (index, event) => {
      dragIndex.value = index
      event.dataTransfer.setData('text/plain', index.toString())
    }

    // 拖拽结束
    const handleDragEnd = () => {
      dragIndex.value = -1
    }

    // 拖拽悬停
    const handleDragOver = (event) => {
      event.preventDefault()
    }

    // 放置
    const handleDrop = (dropIndex, event) => {
      event.preventDefault()
      const draggedIndex = parseInt(event.dataTransfer.getData('text/plain'))
      
      if (draggedIndex !== dropIndex) {
        const draggedItem = teacherList.value[draggedIndex]
        teacherList.value.splice(draggedIndex, 1)
        teacherList.value.splice(dropIndex, 0, draggedItem)
        
        // 更新排序号
        teacherList.value.forEach((teacher, index) => {
          teacher.sortOrder = index + 1
        })
      }
    }

    // 处理主要教师变更
    const handlePrimaryChange = (teacher, value) => {
      teacher.isPrimary = value
      
      // 如果取消了主要教师标记，检查是否还有其他主要教师
      if (!value) {
        const primaryTeachers = teacherList.value.filter(t => t.isPrimary)
        if (primaryTeachers.length === 0) {
          ElMessage.warning('至少需要设置一位主要教师')
          // 延迟恢复勾选状态
          nextTick(() => {
            teacher.isPrimary = true
          })
        }
      }
    }

    // 保存排序
    const handleSave = async () => {
      if (!hasValidPrimary.value) {
        ElMessage.error('请至少设置一位主要教师')
        return
      }

      saving.value = true
      
      try {
        const teacherIds = teacherList.value.map(t => t.id)
        const orders = teacherList.value.map((t, index) => index + 1)
        const primaryFlags = teacherList.value.map(t => t.isPrimary)

        // 如果是已存在的教学任务，调用API保存排序
        if (props.missionId && props.missionId !== null) {
          await teachingMissionApi.reorderTeachers(
            props.missionId,
            teacherIds,
            orders,
            primaryFlags
          )
          ElMessage.success('教师排序保存成功')
        } else {
          // 新建任务时，只是返回排序结果，不调用API
          ElMessage.success('教师排序设置成功')
        }

        emit('success', {
          teachers: teacherList.value,
          orders: orders,
          primaryFlags: primaryFlags
        })
        handleClose()
      } catch (error) {
        console.error('保存教师排序失败:', error)
        ElMessage.error('保存教师排序失败: ' + (error.message || '未知错误'))
      } finally {
        saving.value = false
      }
    }

    // 关闭对话框
    const handleClose = () => {
      dialogVisible.value = false
    }

    return {
      dialogVisible,
      loading,
      saving,
      teacherList,
      dragIndex,
      hasValidPrimary,
      handleDragStart,
      handleDragEnd,
      handleDragOver,
      handleDrop,
      handlePrimaryChange,
      handleSave,
      handleClose
    }
  }
}
</script>

<style scoped>
.teacher-sorting-dialog {
  --el-dialog-border-radius: 8px;
}

.sorting-container {
  min-height: 400px;
}

.mb-4 {
  margin-bottom: 16px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.empty-teachers {
  text-align: center;
  padding: 40px 0;
}

.teacher-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.teacher-item {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  transition: all 0.3s ease;
  cursor: move;
}

.teacher-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.teacher-item.dragging {
  opacity: 0.5;
  transform: scale(1.02);
}

.drag-handle {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  color: #909399;
  cursor: grab;
  margin-right: 12px;
}

.drag-handle:active {
  cursor: grabbing;
}

.teacher-info {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.teacher-basic {
  flex: 1;
}

.teacher-name {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.teacher-details {
  display: flex;
  gap: 16px;
  color: #606266;
  font-size: 14px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.teacher-actions {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
}

.sort-info {
  display: flex;
  align-items: center;
  gap: 4px;
}

.sort-label {
  font-size: 14px;
  color: #606266;
}

.primary-checkbox {
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-alert__content) {
  line-height: 1.6;
}

:deep(.el-alert__content p) {
  margin: 2px 0;
}
</style>